package quanlyhochieu.taomoi;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

import org.apache.myfaces.custom.fileupload.UploadedFile;

import dbutil.ConnectDB;

public class UploadListener implements ValueChangeListener{

	public void processValueChange(ValueChangeEvent event)
			throws AbortProcessingException {
		
	        UploadedFile uploadedFile = (UploadedFile) event.getNewValue();
         	ConnectDB.connectDB();		
			String deleteTable = "delete from luuanhtam";
			String SQL = "INSERT INTO luuanhtam(id,anh) " +
						  " VALUES(?,?)";

			BufferedInputStream bisWrite = null;
			if(uploadedFile != null){
			try {
				System.out.println("ten anh "+uploadedFile.getName());
				bisWrite = new BufferedInputStream(uploadedFile.getInputStream());
			} catch (FileNotFoundException exFile) {
				exFile.printStackTrace();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				ConnectDB.getStatement().executeUpdate(deleteTable);
				PreparedStatement pre = ConnectDB.connect.prepareStatement(SQL);
				pre.setInt(1, 1);
				pre.setBinaryStream(2, bisWrite, (int) uploadedFile.getSize());
				pre.executeUpdate();
			} catch (SQLException se) {
				se.printStackTrace();
				System.out.println(" SQL is invalid");
			}
			}
    }
}
